package com.tang.controller;

import com.alibaba.fastjson2.JSONObject;
import com.tang.dto.BookDTO;
import com.tang.dto.GiteeDTO;
import com.tang.dto.UserDTO;
import com.tang.resp.JsonResp;
import com.tang.service.impl.BookServiceImpl;
import com.tang.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user/*")
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public JsonResp login(@RequestBody UserDTO userDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        UserDTO login = userService.login(userDTO);
        if (ObjectUtils.isNotEmpty(login)){
            String token = UUID.randomUUID().toString();
            login.setToken(token);
            redisTemplate.opsForValue().set(token, JSONObject.toJSONString(login),3600*24, TimeUnit.SECONDS);
            resp.setMessage("用户登录成功");
        }else {
            resp.setMessage("用户登录失败");
        }
        resp.setData(login);
        return resp;
    }
    @PostMapping("callback")
    public JsonResp callback(@RequestBody GiteeDTO giteeDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId("86fe082a7756b738f2b0a32bff08e5745d7c1c1ca3274f4d3432a37d91f98f97")
                .clientSecret("2bb83fa46b52593c2531a6cf5f2a00c76a65149235401e99b8b9f12264aeee44")
                .redirectUri("http://202.81.231.111:14006/callback")
                .build());
        AuthResponse<AuthUser> login = authRequest.login(AuthCallback.builder().state(giteeDTO.getCode()).code(giteeDTO.getUuid()).build());
        System.out.println(login);
//        if (ObjectUtils.isNotEmpty(login)){
//            String token = UUID.randomUUID().toString();
//            login.setToken(token);
//            redisTemplate.opsForValue().set(token, JSONObject.toJSONString(login),3600*24, TimeUnit.SECONDS);
//            resp.setMessage("用户登录成功");
//        }else {
//            resp.setMessage("用户登录失败");
//        }
        resp.setData(login);
        return resp;
    }
    @GetMapping("/preLoginByGitee")
    public JsonResp preLoginByGitee() {
        JsonResp resp = new JsonResp();
        GiteeDTO dto = new GiteeDTO();
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId("86fe082a7756b738f2b0a32bff08e5745d7c1c1ca3274f4d3432a37d91f98f97")
                .clientSecret("2bb83fa46b52593c2531a6cf5f2a00c76a65149235401e99b8b9f12264aeee44")
                .redirectUri("http://localhost/callback")
                .build());
        String uuid = UUID.randomUUID().toString();
        String authorizeUrl = authRequest.authorize(uuid);
        dto.setAuthorizeUrl(authorizeUrl);
        dto.setUuid(uuid);
        return resp;
    }

    @GetMapping("all")
    public JsonResp all(){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("查询用户成功");
        List<UserDTO> all = userService.all();
        resp.setData(all);
        return resp;
    }
    @Validated
    @GetMapping("list")
    public JsonResp list(String loginName, @NotNull int pageNum, @NotNull int pageSize){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("查询用户成功");
        Map<String, Object> map = userService.list( loginName, pageNum, pageSize);
        resp.setData(map);
        return resp;
    }
    @PostMapping("update")
    public JsonResp update(@RequestBody UserDTO userDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        int update = userService.update(userDTO);
        if (update>0){
            resp.setMessage("更新用户成功");
        }else {
            resp.setMessage("更新用户失败");
        }
        resp.setData(update);
        return resp;
    }
    @PostMapping("updatePassword")
    public JsonResp updatePassword(@RequestBody UserDTO userDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        int update = userService.updatePassword(userDTO);
        if (update>0){
            resp.setMessage("更新用户密码成功");
        }else {
            resp.setMessage("更新用户密码失败");
        }
        resp.setData(update);
        return resp;
    }


    @DeleteMapping("delete/{id}")
    public JsonResp delete(@PathVariable("id") String id){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        int delete = userService.delete(id);
        if (delete>0){
            resp.setMessage("删除用户成功");
        }else {
            resp.setMessage("删除用户失败");
        }
        resp.setData(delete);
        return resp;
    }
    @DeleteMapping("logout/{token}")
    public JsonResp logout(@PathVariable("token") String token){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        Boolean delete = redisTemplate.delete(token);
        if (delete){
            resp.setMessage("登出用户成功");
        }else {
            resp.setMessage("登出用户失败");
        }
        resp.setData(delete);
        return resp;
    }
}
